import { parseTime } from '@/utils'
import { Message, Loading } from 'element-ui'
import { exportExcel, exportExcelGet } from '@/api/export'
/**
 *
 * @param {*} url | 接口url
 * @param {*} params | 参数
 * @param {*} fileName | 导出文件名
 * @param {*} methods | 请求方式，不传默认POST
 */
export function exportExcelFun(url, params, fileName, methods = 'post', config = {}) {
  const loading = Loading.service({
    lock: true,
    text: '导出中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const {ctype, dcType = 'xls'} = config
  const exportFun = methods === 'post' ? exportExcel : exportExcelGet
  exportFun(url, params).then(file => {
    // res 二进制
    var blob = new Blob([file], {
      type: ctype || 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'
    }) // application/
    var downloadElement = document.createElement('a')
    var href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = `${fileName}.${dcType}` // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
    loading.close()
  }).catch((e) => {
    loading.close()
  })
}

/**
 * 时间区间范围
 */
export function timeRange(time, limtiDay = 30, message = '') {
  if (time && time.length > 1) {
    const startdate = parseTime(time[0])
    const orderEndTime = parseTime(time[1])
    const startD = new Date(Date.parse(startdate.replace(/-/g, '/')))
    const endD = new Date(Date.parse(orderEndTime.replace(/-/g, '/')))
    const days = parseInt(
      (endD.getTime() - startD.getTime()) / (1000 * 60 * 60 * 24)
    )
    if (days > limtiDay) {
      Message({
        message: message || '处理时间需控制在30天之内~',
        type: 'warning'
      })
      return false
    } else {
      return true
    }
  } else {
    Message({
      message: '请选择处理时间',
      type: 'warning'
    })
    return false
  }
}
